<template>
  <el-dialog
    :title="id ? '编辑物流' : '添加物流'"
    :visible.sync="visible"
    width="400px"
    :before-close="
      () => {
        $emit('close');
      }
    "
  >
    <el-form
      ref="expressForm"
      size="small"
      :rules="rules"
      :model="form"
      label-width="100px"
    >
      <el-form-item label="物流名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="代码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="电话" prop="tel">
        <el-input v-model="form.tel" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addExpress, getExpressDetail } from '@/api/express-mng'
export default {
  props: ['visible', 'id'],
  data() {
    return {
      form: {
        name: null,
        code: null,
        tel: null
      },
      rules: {
        name: [{ required: true, message: '请填写物流名称', trigger: 'blur' }],
        code: [{ required: true, message: '请填写物流代码', trigger: 'blur' }],
        tel: [{ required: true, message: '请填写物流电话', trigger: 'blur' }]
      }
    }
  },
  watch: {
    visible: function(val) {
      if (val) {
        if (this.id) {
          getExpressDetail({ id: this.id }).then(res => {
            if (res.code === 200) {
              this.form.name = res.data.name
              this.form.code = res.data.for_short
              this.form.tel = res.data.mobile
            }
          })
        }
      } else {
        this.$refs['expressForm'].resetFields()
      }
    }
  },
  created() {},
  methods: {
    submit() {
      this.$refs['expressForm'].validate(valid => {
        if (valid) {
          const obj = {
            for_short: this.form.code,
            name: this.form.name,
            mobile: this.form.tel,
            id: this.id ? this.id : undefined
          }
          addExpress(obj).then(res => {
            if (res.code === 200) {
              this.$message({
                message: this.id ? '修改成功' : '添加成功',
                type: 'success'
              })
              this.$emit('close')
            }
          })
        }
      })
    }
  }
}
</script>

<style></style>
